<template>
  <div id="root">
      <!--工具条-->
      <el-col :span="24" class="toolbar">
        <el-form :inline="true" :model="query">
          <el-form-item>
            <el-input v-model="query.keyword" placeholder="关键字"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-on:click="search">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onsale">批量上架</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="offsale">批量下架</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <!--列表-->
      <el-table
        :data="pageInfo.rows"
        highlight-current-row
        v-loading="listLoading"
        height="580"
        @selection-change="selsChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" fixed> </el-table-column>
        <el-table-column type="index" width="60" fixed> </el-table-column>
        <el-table-column prop="title" label="标题" fixed width="150" sortable>
        </el-table-column>
        <el-table-column prop="cover" label="封面" width="120" sortable>
          <template slot-scope="scope">
            <img :src="scope.row.cover" style="width: 75px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="saleprice" label="原价" width="120" sortable>
        </el-table-column>
        <el-table-column prop="costprice" label="售价" width="120" sortable>
        </el-table-column>
        <el-table-column prop="isnew" label="是否新车" width="120" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.isnew == 0">二手车</span>
            <span v-if="scope.row.isnew == 1">新车</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="registertime"
          label="上牌时间"
          width="120"
          sortable
        >
        </el-table-column>
        <el-table-column prop="mileage" label="里程数" width="120" sortable>
        </el-table-column>
        <el-table-column prop="shopname" label="店铺名称" width="100" sortable>
        </el-table-column>
        <el-table-column
          prop="onsaletime"
          label="上架时间"
          width="100"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="offsaletime"
          label="下架时间"
          width="100"
          sortable
        >
        </el-table-column>
        <el-table-column prop="state" label="状态" min-width="100" sortable>
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state == 1" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="costeffective"
          label="超值"
          min-width="100"
          sortable
        >
          <template slot-scope="scope">
            <span v-if="scope.row.costeffective == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column prop="rushsale" label="急售" min-width="100" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.rushsale == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="quasinewcar"
          label="准新车"
          min-width="100"
          sortable
        >
          <template slot-scope="scope">
            <span v-if="scope.row.quasinewcar == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="transitivecountry"
          label="可提全国"
          min-width="100"
          sortable
        >
          <template slot-scope="scope">
            <span v-if="scope.row.transitivecountry == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column prop="type.name" label="类型" width="100" sortable>
        </el-table-column>
        <el-table-column
          prop="seller.realName"
          label="营销人员"
          width="100"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="auditstate"
          label="审核状态"
          width="100"
          sortable
        >
          <template slot-scope="scope">
            <span v-if="scope.row.auditstate == 1">已审核</span>
            <span v-else>未审核</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDel(scope.$index, scope.row)"
              >删除</el-button
            >
            <br />
            <el-button
              size="small"
              v-if="scope.row.state == 0 && scope.row.auditstate == 1"
              @click="handleEdit(scope.$index, scope.row)"
              >上架</el-button
            >
            <el-button
              type="danger"
              size="small"
              v-if="scope.row.state == 1"
              @click="handleDel(scope.$index, scope.row)"
              >下架</el-button
            >
            <br />
            <el-button
              type="danger"
              size="small"
              style="margin-top: 10px"
              @click="handleResource(scope.$index, scope.row)"
              >资源维护</el-button
            >
            <br />
            <el-button
              type="danger"
              size="small"
              style="margin-top: 10px"
              @click="handleDel(scope.$index, scope.row)"
              >上传检测报告</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!--工具条-->
      <el-col :span="24" class="toolbar">
        <el-button
          type="danger"
          @click="batchRemove"
          :disabled="this.sels.length === 0"
          >批量删除</el-button
        >
        <el-pagination
          layout="prev, pager, next"
          :current-page="query.page"
          @current-change="handleCurrentChange"
          :page-size="query.rows"
          :total="pageInfo.total"
          style="float: right"
        >
        </el-pagination>
      </el-col>

      <!--新增/修改界面-->
      <el-dialog
        title="新增/修改"
        :visible.sync="saveFormVisible"
        :close-on-click-modal="false"
      >
        <el-form
          :model="carForm"
          label-width="80px"
          :rules="saveFormRules"
          ref="carForm"
        >
          <el-form-item label="标题">
            <el-input v-model="carForm.title" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="封面">
            <el-upload
              class="upload-demo"
              action="http://localhost:8090/txCos"
              :on-remove="coverHandleRemove"
              :on-success="coverHandleSuccess"
              :file-list="coverFileList"
              list-type="picture"
              :limit="1"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="原价">
            <el-input
              v-model="carForm.saleprice"
              style="width: 220px"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="售价">
            <el-input
              v-model="carForm.costprice"
              style="width: 220px"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否新车">
            <el-radio-group v-model="carForm.isnew">
              <el-radio class="radio" :label="1">是</el-radio>
              <el-radio class="radio" :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上牌时间">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="carForm.registertime"
              type="date"
              placeholder="请选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="里程数">
            <el-input
              v-model="carForm.mileage"
              style="width: 220px"
              type="number"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="超值">
            <el-radio-group v-model="carForm.costeffective">
              <el-radio class="radio" :label="1">是</el-radio>
              <el-radio class="radio" :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="急售">
            <el-radio-group v-model="carForm.rushsale">
              <el-radio class="radio" :label="1">是</el-radio>
              <el-radio class="radio" :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="准新车">
            <el-radio-group v-model="carForm.quasinewcar">
              <el-radio class="radio" :label="1">是</el-radio>
              <el-radio class="radio" :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="可迁全国">
            <el-radio-group v-model="carForm.transitivecountry">
              <el-radio class="radio" :label="1">是</el-radio>
              <el-radio class="radio" :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="车辆类型">
            <el-cascader
              placeholder="请选择"
              v-model="carForm.typeId"
              :options="carTypeTree"
              :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id',
              }"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="基本信息">
            <!-- <el-input
              type="textarea"
              v-model="carForm.carDetail.info"
            ></el-input> -->
            <quill-editor v-model="carForm.carDetail.info" :options="quillOptions">
            </quill-editor>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="saveFormVisible = false">取消</el-button>
          <el-button type="primary" @click.native="save" :loading="addLoading"
            >提交</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        title="资源维护"
        :visible.sync="carResourceVisible"
        :close-on-click-modal="false"
      >
        <el-form label-width="80px" ref="carResourceForm">
          <el-form-item label="主图">
            <el-upload
              class="upload-demo"
              action="http://localhost:8090/txCos"
              :on-remove="imgHandleRemove"
              :on-success="imgHandleSuccess"
              :file-list="imgFileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="副图">
            <el-upload
              class="upload-demo"
              action="http://localhost:8090/txCos"
              :on-remove="viceimgHandleRemove"
              :on-success="viceimgHandleSuccess"
              :file-list="viceimgFileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="更多图片">
            <el-upload
              class="upload-demo"
              action="http://localhost:8090/txCos"
              :on-remove="moreimgHandleRemove"
              :on-success="moreimgHandleSuccess"
              :file-list="moreimgFileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="carResourceVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click.native="saveCarResource"
            :loading="addLoading"
            >提交</el-button
          >
        </div>
      </el-dialog>
  </div>
</template>

<script>
import carApi from "@/api/car/car";
import carTypeApi from "@/api/car/carType";
import shopApi from "@/api/org/shop";

// 引入富文本编辑器quill相关组件
import {quillEditor} from "vue-quill-editor";
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css"
import quillConfig from '@/api/quill-config'
export default {
  components:{
    quillEditor
  },
  data() {
    return {
      listLoading: false,
      sels: [], //列表选中列
      saveFormVisible: false, //新增界面是否显示
      addLoading: false,
      quillOptions:quillConfig,
      saveFormRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        sn: [{ required: true, message: "请输入标识", trigger: "blur" }],
      },
      query: {
        page: 1,
        rows: 6,
        keyword: "",
      },
      pageInfo: {
        rows: [],
        total: 0,
      },
      coverFileList: [], // 封面图片的图片列表
      carForm: {
        id: null,
        title: "",
        cover: "",
        saleprice: 0,
        costprice: 0,
        isnew: 0,
        registertime: "",
        mileage: null,
        costeffective: 0,
        rushsale: 0,
        quasinewcar: 0,
        transitivecountry: 0,
        type: {
          id: null,
          name: "",
        },
        typeId: null,
        lastParentTypeId:null,
        carDetail: {
          id:'',
          info: "",
        },
      },
      carTypeTree: [],
      carId:null,
      carResourceVisible: false,
      carResourceList:[],
      imgFileList: [],
      viceimgFileList: [],
      moreimgFileList: [],
    };
  },
  methods: {
    // 批量上架的方法
    onsale() {
      // 获取当前选中行的id
      var ids = this.sels.map((item) => item.id);
      //获取选中的行
      if (!this.sels || this.sels.length < 1) {
        this.$message({
          message: "老铁，你不选中数据，臣妾上架不了啊....",
          type: "error",
        });
        return;
      }
      this.$confirm("确认上架选中记录吗？", "提示", {
        type: "warning",
      }).then(() => {
          this.listLoading = true;
          carApi.batchOnSale(ids)
            .then(res => {
              this.listLoading = false;
              this.$message.success(res.data.message)
              this.getCars();
            }).catch(res => {
              this.listLoading = false;
            })
        }).catch(() => {});
    },
    // 批量下架
    offsale() {
      var ids = this.sels.map((item) => item.id);
      //获取选中的行
      if (!this.sels || this.sels.length < 1) {
        this.$message({
          message: "老铁，你不选中数据，臣妾下架不了啊....",
          type: "error",
        });
        return;
      }
      this.$confirm("确认下架选中记录吗？", "提示", {
        type: "warning",
      }).then(() => {
          this.listLoading = true;
          carApi.batchOffSale(ids)
            .then(res => {
              this.listLoading = false;
              this.$message.success(res.data.message)
              this.getCars();
            }).catch(res => {this.listLoading = false;});
        }).catch(() => {});
    },
    saveCarResource() {
      this.dealCarResource()
      this.$confirm("确认提交吗？", "提示", {}).then(() => {
        this.addLoading = true;
        carApi.batchInsert(this.carResourceList)
          .then(res => {
            // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
            this.addLoading = false;
            // 关闭弹框
            this.carResourceVisible = false;
            this.$message({ message: "保存成功!", type: "success" });
          }).catch(res => {
            this.addLoading = false;
            this.$message({ message: res.data.message, type: "error" });
          })
      });
    },
    dealCarResource(){
      //主图
      this.imgFileList.forEach(e => {
        this.carResourceList.push({carId:this.carId,resourceUrl:e.response.resultObj,type:1})
      });
      //副图
      this.viceimgFileList.forEach(e => {
        this.carResourceList.push({carId:this.carId,resourceUrl:e.response.resultObj,type:2})
      })
      //更多图
      this.moreimgFileList.forEach(e => {
        this.carResourceList.push({carId:this.carId,resourceUrl:e.response.resultObj,type:3})
      })
    },
    handleResource(index, row) {
      // 给文件数组赋空值,防止将上一次的内容带到这一次
      this.imgFileList = [];
      this.viceimgFileList = [];
      this.moreimgFileList = [];
      // 展示弹框
      this.carResourceVisible = true;
      this.carId = row.id;
      // 根据车辆的ID查询该车辆的资源信息,如果有就要回显
      this.getCarResourcesByCarId(row.id);
    },
    getCarResourcesByCarId(carId) {
      carApi.getResources(carId)
        .then(res => {
          var list = res.data.resultObj
          list.forEach(e => {
            let type = e.type
            let imgurl = e.resourceUrl
            let name = imgurl.substring(imgurl.lastIndexOf("/") + 1);
            if(type == 1){
              this.imgFileList.push({url:imgurl,name:name,response:{resultObj:imgurl}})
            }else if(type == 2){
              this.viceimgFileList.push({url:imgurl,name:name,response:{resultObj:imgurl}})
            }else if(type == 3){
              this.moreimgFileList.push({url:imgurl,name:name,response:{resultObj:imgurl}})
            }
          })
        })
    },
    search() {
      // 点击 查询时,应该重新从第一页开始查询
      this.query.page = 1;
      this.getCars();
    },
    handleCurrentChange(val) {
      // val 当前跳转的页码
      this.query.page = val;
      this.getCars();
    },
    //封面
    coverHandleRemove(file, fileList) {
      var filePath = file.response.resultObj;
      shopApi.delete(filePath)
        .then(response => {
          this.$message({message: '文件删除成功！', type: 'success' });
          this.carForm.cover = "";
        }).catch(response => {
          this.$message({message: '文件删除失败！', type: 'error' });
        })
    },
    coverHandleSuccess(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      this.carForm.cover = response.resultObj;
      this.$message({message: '文件上传成功！', type: 'success' });
      console.log(this.coverFileList)
    },
    // 主图
    imgHandleRemove(file, fileList) {
      var filePath = file.response ? file.response.resultObj : file.url;
      this.imgFileList = fileList
      //删除数据库的
      carApi.deleteResource(filePath)
        .then(res => {}).catch(res => {
          this.$message({ message: "文件删除成功!", type: "success" });
        })
      //删除Cos对象存储的
      carApi.deleteImge(filePath)
        .then(res => {
          this.$message({ message: "文件删除成功!", type: "success" });
        })
    },
    imgHandleSuccess(response, file, fileList) {
      this.imgFileList = fileList
    },
    //副图
    viceimgHandleRemove(file, fileList) {
      var filePath = file.response ? file.response.resultObj : file.url;
      this.viceimgFileList = fileList
      //删除数据库的
      carApi.deleteResource(filePath)
        .then(res => {}).catch(res => {
          this.$message({ message: "文件删除成功!", type: "success" });
        })
      //删除Cos对象存储的
      carApi.deleteImge(filePath)
        .then(res => {
          this.$message({ message: "文件删除成功!", type: "success" });
        })
    },
    viceimgHandleSuccess(response, file, fileList) {
      this.viceimgFileList = fileList
    },
    //更多图
    moreimgHandleRemove(file, fileList) {
      var filePath = file.response ? file.response.resultObj : file.url;
      this.moreimgFileList = fileList
      //删除数据库的
      carApi.deleteResource(filePath)
        .then(res => {}).catch(res => {
          this.$message({ message: "文件删除成功!", type: "success" });
        })
      //删除Cos对象存储的
      carApi.deleteImge(filePath)
        .then(res => {
          this.$message({ message: "文件删除成功!", type: "success" });
        })
    },
    moreimgHandleSuccess(response, file, fileList) {
      this.moreimgFileList = fileList
    },
    //获取汽车列表
    getCars() {
      carApi.getPageList(this.query).then((res) => {
        this.pageInfo = res.data.resultObj;
      });
    },
    //删除
    handleDel(index, row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.listLoading = true;
          this.$http.delete("/car/" + row.id).then((result) => {
            result = result.data;
            if (result.success) {
              // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
              this.listLoading = false;
              // 从第一页开始重新进行查询
              this.search();
              this.$message({ message: "删除成功!", type: "success" });
            } else {
              this.$message({ message: result.message, type: "error" });
            }
          });
        })
        .catch(() => {
          this.$message({ message: "已取消删除", type: "info" });
        });
    },
    //显示编辑界面
    handleEdit(index, row) {
      // 显示弹框
      this.saveFormVisible = true;
      // row就是当前行对象,所以直接将row赋值给this.saveForm就可以实现回显
      this.carForm = Object.assign({}, row);
      if(this.carForm.carDetail == null){
        this.carForm.carDetail = {}
      }
      this.coverFileList = []
      this.coverFileList[0] = {
        url:this.carForm.cover
      }
      this.getCarTypeTree();
    },
    //显示新增界面
    handleAdd() {
      // 显示弹框
      this.saveFormVisible = true;
      // 将this.saveForm中的值赋空值
      this.carForm = {
        id: null,
        title: "",
        cover: "",
        saleprice: 0,
        costprice: 0,
        isnew: 0,
        registertime: "",
        mileage: null,
        costeffective: 0,
        rushsale: 0,
        quasinewcar: 0,
        transitivecountry: 0,
        type: {
          id: null,
          name: "",
        },
        typeId: null,
        carDetail: {
          info: "",
        },
      };
      this.coverFileList = []
      // 查询车辆类型的树
      this.getCarTypeTree();
    },
    getCarTypeTree() {
      carTypeApi.getTree(0)
        .then(res => {
          this.carTypeTree = res.data.resultObj;
        })
    },
    //新增/修改的保存操作
    save() {
      this.$refs.carForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            var param = this.carForm;
            var array = param.typeId;
            if (array && array.length > 0) {
              param.lastParentTypeId = array[0]
              param.typeId = array[array.length - 1] // {id:27}
            }
            this.addLoading = true;
            carApi.saveCar(param)
              .then(res => {
                // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
                this.addLoading = false;
                // 关闭弹框
                this.saveFormVisible = false;
                // 从第一页开始重新进行查询
                this.search();
                this.$message({ message: "保存成功!", type: "success" });
              }).catch(res => {
                this.addLoading = false;
              })
          });
        }
      });
    },
    selsChange(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove() {
      // 拿到要删除行的ID  this.sels是当前被勾选中的多选框的所有行的对象
      var ids = this.sels.map((item) => item.id);
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.listLoading = true;
          this.$http.patch("/car", ids).then((result) => {
            result = result.data;
            if (result.success) {
              // 操作成功:要关闭加载框 刷新当前数据  提示删除成功
              this.listLoading = false;
              // 从第一页开始重新进行查询
              this.search();
              this.$message({ message: "删除成功!", type: "success" });
            } else {
              this.$message({ message: result.message, type: "error" });
            }
          });
        })
        .catch(() => {});
    },
  },
  mounted() {
    this.getCars();
  },
};
</script>

<style scoped>
#root {
  margin: 20px 16px;
}
.toolbar {
  background-color: rgb(244, 243, 244);
  padding-top: 10px;
  padding-left: 10px;
  height: 60px;
}
</style>